package titt.service;

import java.lang.reflect.Method;

import titt.type.Type;
import titt.type.TypedObject;
import titt.type.Types;

public class TITTInternal {

	public static final String 	PING 		= "cumdumpster", 
								INTERFACE	= "showMeYourTITTies";
	
	public int ping() {
		return 42;
	}
	
	public String[][] getInterface(Object o) {
		return getTITTInterface(o.getClass());
	}
	
	private String getType(Class<?> c) {
		return new Type(c).asString();
	}

	private String[][] getTITTInterface(Class<?> c) {
		String[][] ret = new String[1+c.getMethods().length-6][];

		int mc = 0;
		
		ret[mc++] = new String[]{ getType(c) };

		for(Method m : c.getMethods()) {

			Class<?>[] pams = m.getParameterTypes();
			
			String[] mholder = new String[pams.length + 2];

			if(m.getName().equals("notify") && pams.length == 0) continue;
			if(m.getName().equals("notifyAll") && pams.length == 0) continue;
			if(m.getName().equals("getClass") && pams.length == 0) continue;
			if(m.getName().equals("wait") && pams.length == 0) continue;
			if(m.getName().equals("wait") && pams.length == 1 && pams[0].equals(Long.TYPE)) continue;
			if(m.getName().equals("wait") && pams.length == 2 && pams[0].equals(Long.TYPE) && pams[1].equals(Integer.TYPE)) continue;

			mholder[0] = getType(m.getReturnType());
			mholder[1] = m.getName();
			
			for(int i = 0; i < pams.length; i++) {
				mholder[2+i] = getType(pams[i]);
			}

			ret[mc++] = mholder;
		}

		return ret;
	}
	
	public TypedObject call(Object o, String methodName) {
		if(methodName.equals(PING))
			return new TypedObject(Types.INT, ping());
		
		if(methodName.equals(INTERFACE))
			return new TypedObject(Types.toArray(Types.toArray(Types.STRING)), getInterface(o));

		return null;
	}
	
}
